package com.example.backend.controller;

import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.backend.common.EncryptUtil;
import com.example.backend.entity.User;
import com.example.backend.mapper.UserCardMapper;
import com.example.backend.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import static com.example.backend.common.EncryptUtil.encrypt;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@CrossOrigin
@Controller
@RestController
public class SendCodeController {
    @Resource
    UserMapper userMapper;
    static String openId = "";
    @ResponseBody
    @RequestMapping(value = "/send",method = POST)
    public void getOpenid(@RequestParam(value="code",required=false)String code,
                          HttpServletResponse response)
            throws Exception {
        //这里改成自己的
        String appId="wx1234567890";
        String secret="82134128e46652112335c812311194";
        //微信官方提供获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        //替换appid，appsecret，和code
        String requestUrl = WX_URL.replace("APPID", appId).
                replace("SECRET", secret).replace("JSCODE", code).
                replace("authorization_code", "authorization_code");
        //定义json对象
        JSONObject convertValue=new JSONObject();
        //调用get方法
        String  returnValue=GET(requestUrl);
        //解析返回值，对象解析成字符串
        convertValue= (JSONObject) new JSONObject(returnValue);
        System.out.println(returnValue);
        //{"session_key":"tBPlxgT1xUDC73g94hEMEA==","openid":"oJero4hAhrArpVJv8fWlyR3vhG70"}
        openId=(String) convertValue.get("openid");
        //判断openId是否应该要插入
        response.sendRedirect("/user/insert?openId="+openId);
    }
    @RequestMapping(value = "/getOpenId",method = GET)
    public static String PostOpenId(){
        try {
            String encrypt= EncryptUtil.encrypt(openId);
            System.out.println("openid:"+openId);
            return encrypt;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String GET(String url) {
        String result="";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try{
            //构造url对象
            URL realUrl = new URL(url);
            //获取一个对应该URL的URLConnection对象
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常出现");
        }
        //关闭资源
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现异常");
            }
        }
        return result;
    }
}
